package com.franklin.ideaplugin.easytesting.common.resolver.datetype;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.common.entity.DateClass;
import com.franklin.ideaplugin.easytesting.common.entity.MethodParameter;
import com.franklin.ideaplugin.easytesting.common.resolver.IMethodParameterResolver;
import com.franklin.ideaplugin.easytesting.common.utils.JsonUtils;

import java.util.Date;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2023/7/4
 */
public class DateMethodParameterResolver implements IMethodParameterResolver {
    @Override
    public boolean isTarget(MethodParameter methodParameter) {
        return methodParameter.getClassQualifiedName().equals(DateClass.class.getCanonicalName());
    }

    @Override
    public Class<?> resolveType(MethodParameter methodParameter) {
        if (isTarget(methodParameter)){
            DateClass dateClass = JsonUtils.parseObject(methodParameter.getValue(), DateClass.class);
            if (Objects.nonNull(dateClass)){
                try {
                    return Class.forName(dateClass.getQualifiedName());
                } catch (ClassNotFoundException e) {
                    //ignore
                }
            }
        }
        return null;
    }

    @Override
    public Object resolveValue(MethodParameter methodParameter) {
        if (StrUtil.isBlank(methodParameter.getValue())){
            return getDefaultValue(methodParameter);
        }
        DateClass dateClass = JsonUtils.parseObject(methodParameter.getValue(), DateClass.class);
        if (Objects.isNull(dateClass)){
            return getDefaultValue(methodParameter);
        }
        if (Date.class.getCanonicalName().equals(dateClass.getQualifiedName())){
            return DateUtil.parse(dateClass.getDateValue(),dateClass.getDatePattern());
        }
        return getDefaultValue(methodParameter);
    }

    @Override
    public Object getDefaultValue(MethodParameter methodParameter) {
        return null;
    }
}
